﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TotalFreedomKO
{
    public class KoModelSection<TModel> : KoSection<TModel>, IKoHelper<TModel>
    {
        public HtmlHelper HtmlHelper
        {
            get;
            private set;
        }

        public KoModelSection(HtmlHelper htmlHelper)
            : base(htmlHelper.ViewContext)
        {
            HtmlHelper = htmlHelper;
        }
    }

    public class KoPropertySection<TModel, TProperty> : KoSection<TModel>, IKoHelper<TProperty>
    {
        public HtmlHelper HtmlHelper
        {
            get;
            private set;
        }

        public KoPropertySection(HtmlHelper htmlHelper)
            : base(htmlHelper.ViewContext)
        {
            HtmlHelper = htmlHelper;
        }
    }

    public class KoSection<T> : KoSection
    {
        public T Value { get; set; }

        public KoSection(ViewContext viewContext)
            : base(viewContext)
        { 
        }
    }

    public class KoSection : IDisposable
    {
        private readonly ViewContext _viewContext;
        private bool _disposed;

        public KoSection(ViewContext viewContext)
        {
            if (viewContext == null)
            {
                throw new ArgumentNullException("viewContext");
            }

            _viewContext = viewContext;
        }

        public void Dispose()
        {
            Dispose(true /* disposing */);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                _disposed = true;
                EndKoSection();
            }
        }

        public void EndSection()
        {
            Dispose(true);
        }

        private void EndKoSection()
        {
            _viewContext.Writer.Write(" <!-- /ko -->");
            _viewContext.OutputClientValidation();
            _viewContext.FormContext = null;
        }
    }
}